package com.mszlu.blog.controller;

import com.mszlu.blog.common.Result;
import com.mszlu.blog.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


@Slf4j
@RequestMapping("/upload")
@RestController
public class UploadController {

    @Value("${qiniu.url}")
    private String qiniuUrl;

    @Autowired
    private QiniuUtils qiniuUtils;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){

        //file是一个临时文件，需要转存，不然本次请求之后会销毁
        log.info(file.toString());

        //原始文件名字
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //上传图片到图片服务器，降低自生应用服务器的带宽消耗
        //这里使用 七牛云 按量付费，速度快
        boolean upload = qiniuUtils.upload(file, fileName);
        //上传成功  则返回文件的路径
        if (upload){
            return Result.success(qiniuUrl + fileName);
        }
        //上传失败  范围错误码
        return Result.error(20001,"图片上传失败");
    }

}
